package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.domain.FixedReadingDevice;
import com.csproj.basic.service.FixedReadingDeviceService;
import com.csproj.basic.service.PDAService;
import com.csproj.basic.service.dto.FixedReadingDeviceDTO;
import com.csproj.basic.service.dto.PDADTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * REST controller for managing Warehouse.
 */
/**
 * 读写设备管理的resource
 *
 *  TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 *  TODO url定义遵循/api/gateway（服务名）/v1/资源名
 *  TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 *
 *  TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class FixedReadingDeviceResource {

    private final Logger log = LoggerFactory.getLogger(FixedReadingDeviceResource.class);

    private static final String ENTITY_NAME = "fixedReadingDevice";

    private final FixedReadingDeviceService fixedReadingDeviceService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public FixedReadingDeviceResource(FixedReadingDeviceService fixedReadingDeviceService,UserInfoService userInfoService,SysLogsService sysLogsService) {
        this.fixedReadingDeviceService = fixedReadingDeviceService;
        this.sysLogsService = sysLogsService;
        this.userInfoService = userInfoService;
    }

    /**
     * POST  /fixdevices : 创建pda
     * @param deviceDto deviceDto
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/fixdevices")
    @Timed
    public BaseDTO createFixedReadingDevice(@Valid @RequestBody FixedReadingDeviceDTO deviceDto){
        FixedReadingDeviceDTO result = fixedReadingDeviceService.saveAndGetDTO(deviceDto);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_fixdevice","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * PUT  /fixdevices : 修改pda信息.
     * @param dto  pdaDTO
     * @return
     */
    @PutMapping("/fixdevices/{id}")
    @Timed
    public BaseDTO updateFixedReadingDevice(@Valid @RequestBody FixedReadingDeviceDTO dto, @PathVariable String id) throws URISyntaxException {
        dto.setId(id);
        FixedReadingDeviceDTO result = fixedReadingDeviceService.updateAndGetDTO(dto);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_fixdevice","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /fixdevices : 获取pda信息.
     * @return pda信息
     */
    @GetMapping("/fixdevices")
    @Timed
    public BaseDTO getPageFixedReadingDevices(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                @RequestParam(value = "deviceNo",required = false) String deviceNo,
                                @RequestParam(value = "siteId",required = false) String siteId) {
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("deviceNo",deviceNo);
        map.put("siteId",siteId);
        BaseDTO result = fixedReadingDeviceService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_fixdevice_list","");
        return result;
    }


    /**
     * GET  /fixdevices : 获取读取设备信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allfixdevices")
    @Timed
    public BaseDTO getAllFixedReadingDevices() {
        return BaseDTO.createBaseDTO().setFieldList(fixedReadingDeviceService.findAll());
    }

    /**
     * GET  /fixdevices/:id : 根据设备id，获取读取设备信息
     *
     * @param id id
     * @return pda信息
     */
    @GetMapping("/fixdevices/{id}")
    @Timed
    public BaseDTO getFixedReadingDevice(@PathVariable String id) {
        FixedReadingDeviceDTO fixedReadingDeviceDTO = fixedReadingDeviceService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(fixedReadingDeviceDTO);
    }

    /**
     * DELETE  /fixdevices/:id : 根据id，删除读取设备信息.
     * @param id id
     * @return
     */
    @DeleteMapping("/fixdevices/{id}")
    @Timed
    public BaseDTO deleteFixedReadingDevice(@PathVariable String id) {
        fixedReadingDeviceService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * PUT  /fixdevices/updateDeviceStatus/{id} : 修改pda使用状态
     *
     * @param fixedReadingDeviceDTO
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/fixdevices/updateDeviceStatus/{id}")
    @Timed
    public BaseDTO updateDeviceStatus(HttpServletRequest request, @RequestBody(required = false) FixedReadingDeviceDTO fixedReadingDeviceDTO, @PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", fixedReadingDeviceDTO);
        fixedReadingDeviceDTO.setId(id);
        FixedReadingDeviceDTO result = fixedReadingDeviceService.updateDeviceStatus(fixedReadingDeviceDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_fixdevice_list","");
        return BaseDTO.createBaseDTO(result).setMessage("user_update_fixdevice_success");
    }

    /**
     * PUT  /fixdevices/updateEnable/{id} : 修改电子关锁使用状态
     *
     * @param dto
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/fixdevices/updateEnable/{id}")
    @Timed
    public BaseDTO updateFixedReadingDeviceEnable(@RequestBody(required = false) FixedReadingDeviceDTO dto, @PathVariable String id) throws URISyntaxException {
        dto.setId(id);
        if (dto.getId() == null) {
            return createFixedReadingDevice(dto);
        }
        FixedReadingDeviceDTO result = fixedReadingDeviceService.status(dto.getId(),dto.isEnableFlag());
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_fixdevice_list","");
        return BaseDTO.createBaseDTO(result).setMessage("user_update_fixdevice_status_success");
    }

    /**
     * 查询固定式库存
     * @return
     */
    @GetMapping("/fixdevices/statistics")
    @Timed
    public BaseDTO getFixdevicestatistics(){
        Map<String,Object> result = fixedReadingDeviceService.getStatistics();
        return BaseDTO.createBaseDTO(result);
    }


    /**
     *  批量导入
     */
    @PostMapping("/fixdevices/batchImport")
    @Timed
    public BaseDTO fixBatchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_batch_import_fix","");
        return fixedReadingDeviceService.batchImport(file) ;
    }
}